const App = getApp()
import { CouponModel } from '../../../../models/coupon.js'
const ModelCoupon = new CouponModel()

Page({
  data:{
    select:false,
    availableCouponList:[],
    unavailableCouponList:[],
    couponKey:'',
    couponId:'',
    statusBarHeight: App.globalData.statusBarHeight,
    isTabbar:false
  },
  onLoad:function(options){
    if(options.couponId){
      this.setData({
        couponId:options.couponId
      })
    }
    this.setData({
      couponKey:options.couponKey
    })
    this.chooseCoupon();
  },
  //获取优惠券信息
  chooseCoupon(){
    const self = this;
    const params = {
      couponKey:self.data.couponKey
    }
    ModelCoupon.chooseCoupon(params).then(res => {
      if(self.data.couponId){
        for(var i in res.data.chooseCoupon.availableCouponList){
          res.data.chooseCoupon.availableCouponList[i].select = false;
          if(res.data.chooseCoupon.availableCouponList[i].id == self.data.couponId){
            res.data.chooseCoupon.availableCouponList[i].select = true;
          }
        }
      }
      self.setData({
        availableCouponList:res.data.chooseCoupon.availableCouponList,
        unavailableCouponList:res.data.chooseCoupon.unavailableCouponList
      })
    }).catch();
  },
  //不适用优惠券
  select(){
    const couponList = this.data.availableCouponList
    for(var i in couponList){
      couponList[i].select = false;
    }
    this.setData({
      select:true,
      availableCouponList:couponList
    })
    const pages = getCurrentPages();
    const currPage = pages[pages.length - 1]; //当前页面
    const prevPage = pages[pages.length - 2]; //上一个页面
    prevPage.setData({
      gold:null,
      inputGoldNumber:'',
      couponId:'',
      goldShow : false,
      tipShow: false
    })
    
    //返回订单结算页
    wx.navigateBack({
      delta: 1
    })
  },
  //选择优惠券
  selectItem(e){
    const self = this;
    const index = e.currentTarget.dataset.index;
    const couponList = self.data.availableCouponList
    for(var i in couponList){
      couponList[i].select = false;
    }
    couponList[index].select = true;
    self.setData({
      select:false,
      availableCouponList:couponList
    })
    const pages = getCurrentPages();
    const currPage = pages[pages.length - 1]; //当前页面
    const prevPage = pages[pages.length - 2]; //上一个页面
    // if(couponList[index].couponType == 3){
    //   console.log('商品价格：'+prevPage.data.goodsMoney)
    //   couponList[index].couponAmount = prevPage.data.goodsMoney * (1-couponList[index].percentOff)
    // }
    prevPage.setData({
      gold:null,
      inputGoldNumber:'',
      couponId:couponList[index].id,
      tipShow: false
    })
    wx.navigateBack({
      delta: 1
    })
  }
})